package com.iie.bigVideo.service.impl;

import com.iie.bigVideo.entity.SysUser;
import com.iie.bigVideo.entity.User;
import com.iie.bigVideo.entity.UserCatalog;
import com.iie.bigVideo.entity.dto.UserDto;
import com.iie.bigVideo.mapper.SysUserMapper;
import com.iie.bigVideo.mapper.UserCatalogMapper;
import com.iie.bigVideo.mapper.UserMapper;
import com.iie.bigVideo.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iie.bigVideo.utils.MD5Utils;
import com.iie.bigVideo.utils.ResultUtils;
import com.iie.bigVideo.utils.UUIDUtils;
import com.iie.bigVideo.vo.ResultVO;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XXX
 * @since 2023-11-19
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Value("${file.uploadFile}")
    private String uploadFile;
    @Value("${file.uploadFolder}")
    private String uploadFolder; // 静态资源实际存储路径
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserCatalogMapper userCatalogMapper;

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public ResultVO<SysUser> userLogin(String username, String password) {
        if (!StringUtils.isAnyBlank(username) && !StringUtils.isAnyBlank(password)) {
            //说明不为空
            SysUser sysUser = sysUserMapper.queryByUserName(username);
            if (sysUser == null) {
                //说明没此用户
                return ResultUtils.error(201, "false", "登录失败，用户名不存在！");
            } else {
                //说明有此用户，开始校验密码是否正确
//                String passwordMd5 = MD5Utils.encodeBase64(password);
                if (password.equals(sysUser.getUserPassword())) {
                    //说明密码正确
                    return ResultUtils.success(sysUser);
                } else {
                    return ResultUtils.error(201, "false", "登录失败，密码错误！");
                }

            }
        }
        return ResultUtils.error(500, "false", "服务器异常！");
    }

    /**
     * 修改密码
     *
     * @param userId
     * @param password
     * @return
     */
    @Override
    public ResultVO updatePassword(int userId, String password) {
        if (userId > 0 && !StringUtils.isAnyBlank(password)) {
            //说明不为空
            SysUser sysUser = sysUserMapper.queryByUserId(userId);
            if (sysUser != null) {
//                String passwordMd5 = MD5Utils.encodeBase64(password);
                Boolean updateByUserId = sysUserMapper.updateByUserId(userId, password);
                return ResultUtils.success(updateByUserId);
            }
            return ResultUtils.error(201, "false", "用户名不存在！");
        }
        return ResultUtils.error(500, "false", "服务器异常！");
    }

    /**
     * 导出excel模板
     */
    @Override
    public ResultVO outExcel() {
        //创建一张工作簿workbook
        Workbook workbook = new XSSFWorkbook();
        //在工作簿中创建一张表sheet
        Sheet sheet = workbook.createSheet("sheet1");
        //在表中创建一行row1，对应是sheet.createRow(0);
        Row row1 = sheet.createRow(0);
        //第一个单元格是姓名，第二个单元格是学好，相当于表头
        Cell cell0 = row1.createCell(0);
        cell0.setCellValue("编号");
        Cell cell1 = row1.createCell(1);
        cell1.setCellValue("用户账户(唯一)");
        Cell cell2 = row1.createCell(2);
        cell2.setCellValue("代理人手机号");
        Cell cell3 = row1.createCell(3);
        cell3.setCellValue("用户密码");
        Cell cell4 = row1.createCell(4);
        cell4.setCellValue("园区名称");
        Cell cell5 = row1.createCell(5);
        cell5.setCellValue("启用状态(0是启用|1是禁用)");
        Cell cell6 = row1.createCell(6);
        cell6.setCellValue("时效范围(年-月-日~年-月-日)");
        Cell cellNew1 = row1.createCell(7);
        cellNew1.setCellValue("目录ID(多个ID之间以\"-\"分割)");
        Cell cellNew2 = row1.createCell(8);
        cellNew2.setCellValue("目录时效范围(年-月-日~年-月-日)(多个时间之间以\"&\"分割)");
        //在表中创建第二行row2,对应是sheet.createRow(1);
        Row row2 = sheet.createRow(1);
        //第二行第一个单元格是张三，手机号是123456
        Cell cell01 = row2.createCell(0);
        cell01.setCellValue("1");
        Cell cell7 = row2.createCell(1);
        cell7.setCellValue("zhangsan");
        Cell cell8 = row2.createCell(2);
        cell8.setCellValue("18635205076");
        Cell cell9 = row2.createCell(3);
        cell9.setCellValue("123");
        Cell cell10 = row2.createCell(4);
        cell10.setCellValue("希望幼儿园");
        Cell cell11 = row2.createCell(5);
        cell11.setCellValue("0");
        Cell cell12 = row2.createCell(6);
        cell12.setCellValue("2023-12-01~2023-12-15");
        Cell cell13 = row2.createCell(7);
        cell13.setCellValue("49-20-80");
        Cell cell14 = row2.createCell(8);
        cell14.setCellValue("2023-12-01~2023-12-15");
        //现在的前后端分离项目，应该都是使用的数据流  https://blog.csdn.net/qq_35764460/article/details/117446777
        try {
            //测试阶段使用文件流
            File file = new File(Class.class.getClass().getResource("/").getPath() + uploadFolder);
            //              /www/server/nginx/html/little_bear_u_rent_image/schoolPcFiles/
            if (!file.exists()) {
                file.mkdirs();//没有就创建
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file + "/上传信息模板.xlsx");
            workbook.write(fileOutputStream);
            fileOutputStream.close();//关闭流
            return ResultUtils.success(true);
        } catch (IOException e) {
//            return ResultUtils.error(500, "false", "服务器异常！");
            throw new RuntimeException(e);
        }
    }

    /**
     * 导入excel
     * https://blog.csdn.net/qq_59456579/article/details/130888867
     *
     * @return
     */
    @Override
    @Transactional
    public ResultVO inputExcel(MultipartFile excelFile) {
        if (excelFile == null || excelFile.isEmpty()) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        try {
            List<UserDto> userList = new ArrayList<>();
            Workbook workbook = WorkbookFactory.create(excelFile.getInputStream());
            Sheet sheet = workbook.getSheetAt(0); //获取第一张sheet表
            // 获取总行数
            int totalRows = sheet.getPhysicalNumberOfRows();
            // 获取表头的总列数
            int totalCols = sheet.getRow(0).getPhysicalNumberOfCells();
            //遍历行
            for (int i = 0; i < totalRows; i++) {
                UserDto user = new UserDto();
                //遍历列
                for (int j = 0; j < totalCols; j++) {
                    Cell cell1 = sheet.getRow(i).getCell(1);
                    if (cell1 == null) {
                        return ResultUtils.error(201, "false", "用户账户不能为空！");
                    }
                    cell1.setCellType(Cell.CELL_TYPE_STRING);//转成字符串类型
                    user.setUserName(cell1.getStringCellValue());//用户账号
                    Cell cell2 = sheet.getRow(i).getCell(2);
                    if (cell2 == null) {
                        return ResultUtils.error(201, "false", "代理人手机号不能为空！");
                    }
                    cell2.setCellType(Cell.CELL_TYPE_STRING);//转成字符串类型
                    user.setUserPhone(cell2.getStringCellValue());//手机号
                    Cell cell3 = sheet.getRow(i).getCell(3);
                    if (cell3 == null) {
                        return ResultUtils.error(201, "false", "用户密码不能为空！");
                    }
                    cell3.setCellType(Cell.CELL_TYPE_STRING);//转成字符串类型
                    user.setUserPassword(cell3.getStringCellValue());//密码
                    Cell cell4 = sheet.getRow(i).getCell(4);
                    cell4.setCellType(Cell.CELL_TYPE_STRING);//转成字符串类型
                    user.setNurserySchoolName(cell4.getStringCellValue());//园区名
                    Cell cell5 = sheet.getRow(i).getCell(5);
                    if (cell5 == null) {
                        return ResultUtils.error(201, "false", "启用状态不能为空！");
                    }
                    cell5.setCellType(Cell.CELL_TYPE_STRING);//转成字符串类型
                    if (cell5.getStringCellValue().length() <= 1) {
                        user.setUserIsDeleted(Integer.valueOf(cell5.getStringCellValue()));//启用状态
                    }
                    Cell cell6 = sheet.getRow(i).getCell(6);
                    cell6.setCellType(Cell.CELL_TYPE_STRING);//转成字符串类型
                    user.setUserAssert(cell6.getStringCellValue());//时效范围
                    user.setUserCreatedTime(new Date());//创建时间
                    user.setUserUpdatedTime(new Date());//更新时间
                    Cell cell7 = sheet.getRow(i).getCell(7);
                    if (cell7 == null) {
                        return ResultUtils.error(201, "false", "目录无数据！");
                    }
                    cell7.setCellType(Cell.CELL_TYPE_STRING);//转成字符串类型
                    user.setExcelCatalogId(cell7.getStringCellValue());//目录Id 多个
                    Cell cell8 = sheet.getRow(i).getCell(8);
                    if (cell8 == null) {
                        return ResultUtils.error(201, "false", "目录时效无数据！");
                    }
                    cell8.setCellType(Cell.CELL_TYPE_STRING);//转成字符串类型
                    user.setExcelCatalogTime(cell8.getStringCellValue());//目录时间 多个
                }
//                System.out.println(user.toString());
                userList.add(user);
            }
//            for (Row cells : sheet) {
//                UserDto user = new UserDto();
//                user.setUserName(cells.getCell(1).getStringCellValue());//用户账号
//                user.setUserPhone(cells.getCell(2).getStringCellValue());//手机号
//                user.setUserPassword(cells.getCell(3).getStringCellValue());//密码
//                user.setNurserySchoolName(cells.getCell(4).getStringCellValue());//园区名
//                if (cells.getCell(5).getStringCellValue().length() <= 1) {
//                    user.setUserIsDeleted(Integer.valueOf(cells.getCell(5).getStringCellValue()));//启用状态
//                }
//                user.setUserAssert(cells.getCell(6).getStringCellValue());//时效范围
//                user.setUserCreatedTime(new Date());//创建时间
//                user.setUserUpdatedTime(new Date());//更新时间
//                user.setExcelCatalogId(cells.getCell(7).getStringCellValue());//目录Id 多个
//                user.setExcelCatalogTime(cells.getCell(8).getStringCellValue());//目录时间 多个
//                userList.add(user);
//            }
            if (userList.isEmpty()) {
                return ResultUtils.error(201, "false", "无数据！");
            }
            //根据对象属性进行去重  这一行代码使用 Collections 类的 reverse 方法，将 userList 列表中的元素顺序进行反转
            Collections.reverse(userList);
            //通过 stream() 方法将 userList 转换为一个流
            ArrayList<UserDto> collect = userList.stream().collect(
                    //将流中的元素收集到一个 TreeSet 中。TreeSet 是一个有序的集合，并且使用提供的比较器（Comparator.comparing(User::getUserName)）对元素进行排序。在这里，按照 User 对象的 userName 属性进行排序，以去除重复元素
                    Collectors.collectingAndThen(
                            //第一个参数是要包装的收集器，第二个参数是一个转换函数
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(UserDto::getUserName))), ArrayList::new));
            collect.remove(collect.size() - 1); //去除标题
            //插入数据库
            if (collect.isEmpty()) {
                return ResultUtils.error(201, "false", "无数据！");
            }
            Integer integer = userMapper.addUserList(collect);//用户插入数据库
            ResultVO resultVO = addUserCatalog(collect);//中间表插入信息
            if (resultVO.getData() == null) {
                return ResultUtils.error(201, "false", resultVO.getDescription());
            }
            return ResultUtils.success(integer);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增中间表数据
     */
    @Transactional
    public ResultVO addUserCatalog(List<UserDto> list) {
        List<UserCatalog> userCatalogList = new ArrayList<>();
        Integer userId = null;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getUserId() != null) {
                userId = list.get(i).getUserId();//赋值一个
            }
            list.get(i).setUserId(userId + i);//新增id
            String[] splitId = list.get(i).getExcelCatalogId().split("-");//目录id  49-20-80
            String[] splitTime = list.get(i).getExcelCatalogTime().split("&");//目录时间范围  2023-12-01~2023-12-15&2023-12-01~2023-12-15
            if (splitId.length != splitTime.length) {
                //删除插入的用户信息
                Integer integer = userMapper.deleteByUserID(list.get(0).getUserId());
                //个数不一致
                return ResultUtils.error(201, "false", "目录和目录时效个数不一致！");
            }
            for (int i1 = 0; i1 < splitId.length; i1++) {
                UserCatalog userCatalog = new UserCatalog();
                userCatalog.setUserId(list.get(i).getUserId());//用户id
                userCatalog.setCatalogId(Integer.valueOf(splitId[i1]));//目录ID
                userCatalog.setUserCatalogAssert(splitTime[i1]);//目录ID时间范围
                userCatalogList.add(userCatalog);
            }
        }
        if (userCatalogList.isEmpty()) {
            return ResultUtils.error(201, "false", "无数据！");
        }
        //批量插入数据库
        Integer integer = userCatalogMapper.addUserCatalog(userCatalogList);
        return ResultUtils.success(integer);
    }
}
